<template>
  <div>
    <n-grid class="mt-0" cols="52" responsive="screen" :x-gap="8">
      <n-gi span="12">
        <n-card :segmented="{ content: true }" :bordered="false" size="small" style="height: 100%">
          <template #header>
            <n-space>
              <n-dropdown trigger="hover" @select="handleAddDict" :options="addDictOptions">
                <n-button type="info" ghost icon-placement="right">
                  添加字典
                  <template #icon>
                    <div class="flex items-center">
                      <n-icon size="14">
                        <DownOutlined />
                      </n-icon>
                    </div>
                  </template>
                </n-button>
              </n-dropdown>

              <n-button
                type="info"
                ghost
                icon-placement="left"
                @click="handleEditDictType"
                v-permission="{ action: ['dictManage_change'] }"
              >
                <template #icon>
                  <div class="flex items-center">
                    <n-icon size="14">
                      <EditOutlined />
                    </n-icon>
                  </div>
                </template>
                修改
              </n-button>

              <n-button
                type="info"
                ghost
                icon-placement="left"
                @click="handleDeleteDictType"
                v-permission="{ action: ['dictManage_delete'] }"
              >
                <template #icon>
                  <div class="flex items-center">
                    <n-icon size="14">
                      <DeleteOutlined />
                    </n-icon>
                  </div>
                </template>
                删除
              </n-button>
            </n-space>
          </template>

          <div class="w-full menu">
            <DictTypeTree
              :tree-data="dictTypeTreeData"
              :tree-props="treeProps"
              :checkable="false"
              @selected-tree="handleSelectTree"
              @button-add="() => handleAddDict('child')"
              :is-add="true"
            />
          </div>
        </n-card>
      </n-gi>

      <n-gi span="40">
        <n-card
          :segmented="{ content: true }"
          :bordered="false"
          size="small"
          style="height: 100%; padding-top: 8px"
        >
          <BasicTable
            ref="tableRef"
            :pagination="false"
            :columns="columns"
            :request="fetchDictData"
            :before-request="beforeRequest"
            :row-key="(row) => row.dictId"
            :action-column="actionColumn"
            @checked-row-keys="handleCheckedRowKeys"
            @single-click="handleSingleClick"
          >
            <template #tableTitle>
              <n-button
                type="primary"
                @click="handleAddDictData"
                v-permission="{ action: ['dictManage_add'] }"
              >
                <template #icon>
                  <n-icon>
                    <PlusOutlined />
                  </n-icon>
                </template>
                新增
              </n-button>
            </template>
          </BasicTable>
        </n-card>
      </n-gi>
    </n-grid>

    <CreateDictTypeDrawer ref="createDictTypeRef" :title="drawerTitle" @reload="loadDictTypeTree" />

    <CreateDictDataDrawer
      ref="createDictDataRef"
      :dict-type="selectedDictType.dictType"
      @reload="reloadTable"
    />
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, onMounted, computed, h, nextTick } from 'vue';
  import { useDialog, useMessage, NTag } from 'naive-ui';
  import { DownOutlined, EditOutlined, DeleteOutlined, PlusOutlined } from '@vicons/antd';
  import { BasicTable, TableAction } from '@/components/Table';
  import DictTypeTree from './DictTypeTree.vue';
  import CreateDictTypeDrawer from './CreateDictTypeDrawer.vue';
  import CreateDictDataDrawer from './CreateDictDataDrawer.vue';

  // API 导入
  import {
    getDictTypeTree,
    deleteDictType,
    selectAllByType,
    deleteDictData,
  } from '@/api/business/dist';

  // 类型定义
  interface DictType {
    dictTypeId: string;
    dictNm: string;
    parentId: string;
    parentName: string;
    dictType: string;
    isSys: number;
    child?: DictType[];
  }

  interface DictData {
    dictId: string;
    dictValue: string;
    dictLabel: string;
    dictType: string;
    isSys: number;
    sort: number;
  }

  const dialog = useDialog();
  const message = useMessage();

  // Refs
  const tableRef = ref();
  const createDictTypeRef = ref();
  const createDictDataRef = ref();

  // 数据状态
  const dictTypeTreeData = ref<DictType[]>([]);
  const selectedDictTypeKeys = ref<string[]>([]);
  const selectedDictType = reactive({
    dictTypeId: '',
    dictNm: '',
    parentId: '',
    parentName: '',
    dictType: '',
    isSys: 0,
  });
  const drawerTitle = ref('');
  const loading = ref(true);

  // 树形组件属性
  const treeProps = {
    key: 'dictTypeId',
    label: 'dictNm',
    children: 'child',
  };

  // 表格列配置
  const columns = [
    {
      type: 'selection',
      disabled(row: any) {
        return row.name === 'disabled';
      },
    } as any,
    {
      title: '序号',
      key: 'id',
      width: 20,
      align: 'center',
      className: '',
      render(row: DictData, index: number) {
        return `${index + 1}`;
      },
    },
    {
      title: '键',
      key: 'dictValue',
      width: 20,
      align: 'right',
    },
    {
      title: '值',
      key: 'dictLabel',
      width: 60,
      align: 'left',
    },
    {
      title: '字典类型',
      key: 'dictType',
      width: 50,
      align: 'center',
    },
    {
      title: '系统字典',
      key: 'isSys',
      width: 30,
      align: 'center',
      render(row: DictData) {
        return h(
          NTag,
          {
            type: row.isSys === 1 ? 'error' : 'success',
          },
          {
            default: () => (row.isSys === 1 ? '是' : '否'),
          }
        );
      },
    },
    {
      title: '排序',
      key: 'sort',
      width: 20,
      align: 'center',
    },
  ];

  // 是否禁用添加子字典
  const isAddChildDisabled = computed(() => {
    return !selectedDictTypeKeys.value.length;
  });

  // 添加字典选项
  const addDictOptions = ref([
    {
      label: '添加根字典',
      key: 'root',
      disabled: false,
    },
    {
      label: '添加字典',
      key: 'child',
      disabled: isAddChildDisabled,
    },
  ]);

  // 操作列配置
  const actionColumn = {
    width: 50,
    title: '操作',
    key: 'action',
    fixed: 'right',
    align: 'center',
    render(record: DictData) {
      return h(TableAction, {
        style: 'button',
        actions: createActionButtons(record),
      });
    },
  };

  // 创建操作按钮
  function createActionButtons(record: DictData) {
    return [
      {
        label: '编辑',
        type: 'primary',
        icon: EditOutlined,
        onClick: handleEditDictData.bind(null, record),
        ifShow: () => true,
        disabled: record.isSys === 1,
        auth: ['dictManage_change'],
      },
      {
        label: '删除',
        type: 'error',
        icon: DeleteOutlined,
        onClick: handleDeleteDictData.bind(null, record),
        ifShow: () => true,
        disabled: record.isSys === 1,
        auth: ['dictManage_delete'],
      },
    ];
  }

  // 处理编辑字典数据
  function handleEditDictData(record: DictData) {
    createDictDataRef.value.showModal('编辑字典数据');
    nextTick(() => {
      createDictDataRef.value.setFormData(record);
    });
  }

  // 处理添加字典数据
  function handleAddDictData() {
    createDictDataRef.value.showModal('新增字典数据');
  }

  // 处理删除字典数据
  function handleDeleteDictData(record: DictData) {
    dialog.info({
      title: '提示',
      content: `您确定要删除字典数据<${record.dictLabel}>吗？`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        try {
          const params = {
            id: record.dictId,
          };
          await deleteDictData(params);
          message.success('删除成功');
          reloadTable();
        } catch (error) {
          message.error('删除失败: ' + (error.message || '未知错误'));
        }
      },
      onNegativeClick: () => {},
    });
  }

  // 组件挂载时加载数据
  onMounted(() => {
    loadDictTypeTree();
  });

  // 处理添加字典
  function handleAddDict(key: string) {
    drawerTitle.value = key === 'root' ? '添加根字典' : `添加字典：${selectedDictType.dictNm}`;

    openCreateDictTypeDrawer(key);
  }

  // 打开创建字典类型抽屉
  function openCreateDictTypeDrawer(key: string) {
    const { openDrawer, openRootDrawer } = createDictTypeRef.value;
    if (key === 'child') {
      openDrawer(selectedDictType, true);
    } else {
      openRootDrawer();
    }
  }

  // 处理编辑字典类型
  function handleEditDictType() {
    const { openDrawer } = createDictTypeRef.value;
    openDrawer(selectedDictType, false);
  }

  // 处理选择树节点
  function handleSelectTree(keys: string[]) {
    if (keys.length) {
      // 查找选中的字典类型
      const findDictType = (data: DictType[], key: string): DictType | null => {
        for (const item of data) {
          if (item.dictTypeId === key) {
            return item;
          }
          if (item.child && item.child.length) {
            const found = findDictType(item.child, key);
            if (found) {
              return found;
            }
          }
        }
        return null;
      };

      const dictType = findDictType(dictTypeTreeData.value, keys[0]);
      if (dictType) {
        selectedDictTypeKeys.value = keys;
        Object.assign(selectedDictType, dictType);

        // 设置父级名称
        if (dictType.parentId && dictType.parentId !== '0') {
          const parentDictType = findDictType(dictTypeTreeData.value, dictType.parentId);
          if (parentDictType) {
            selectedDictType.parentName = parentDictType.dictNm;
          }
        } else {
          selectedDictType.parentName = '';
        }
      }
    } else {
      selectedDictTypeKeys.value = [];
      Object.assign(selectedDictType, {
        dictTypeId: '',
        dictNm: '',
        parentId: '',
        parentName: '',
        dictType: '',
        isSys: 0,
      });
    }

    reloadTable();
  }

  // 处理删除字典类型
  function handleDeleteDictType() {
    dialog.info({
      title: '提示',
      content: '您确定想删除此字典类型吗?',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        try {
          const params = {
            id: selectedDictType.dictTypeId,
          };
          await deleteDictType(params);
          message.success('删除成功');
          loadDictTypeTree();
        } catch (error) {
          message.error('删除失败: ' + (error.message || '未知错误'));
        }
      },
    });
  }

  // 获取字典数据
  async function fetchDictData() {
    if (!selectedDictType.dictType) {
      return [];
    }

    try {
      const params = {
        type: selectedDictType.dictType,
      };
      const result = await selectAllByType(params);
      // TODO 应该转换成table识别的格式
      return {
        list: result,
        itemCount: result.length,
      };
    } catch (error) {
      message.error('获取字典数据失败: ' + (error.message || '未知错误'));
      return [];
    }
  }

  // 请求前处理
  function beforeRequest(params: any) {
    return params;
  }

  // 重新加载表格
  function reloadTable() {
    tableRef.value.reload();
  }

  // 加载字典类型树
  async function loadDictTypeTree() {
    try {
      loading.value = true;
      const result = await getDictTypeTree({});
      dictTypeTreeData.value = result || [];

      // 默认选中第一个
      if (dictTypeTreeData.value.length > 0) {
        handleSelectTree([dictTypeTreeData.value[0].dictTypeId]);
      }
    } catch (error) {
      message.error('加载字典类型失败: ' + (error.message || '未知错误'));
    } finally {
      loading.value = false;
    }
  }

  // 处理选中行键值
  function handleCheckedRowKeys(keys: string[]) {
    // 处理选中的行键值
  }

  // 处理单击行
  function handleSingleClick(record: DictData) {
    // 处理单击行事件
  }
</script>

<style scoped>
  .flex {
    display: flex;
  }

  .items-center {
    align-items: center;
  }

  .w-full {
    width: 100%;
  }

  .menu {
    /* 根据需要添加样式 */
  }
</style>
